import instance from "./instance";
import { AnyObject, attachPropertiesToComponent } from "../components";
import authencation from '../plugins/authencation'
import { Method } from "axios";

// 'get' | 'post' | 'delete' | 'GET' | 'POST' | 'DELETE' | 'patch' | 'PATCH'
export type ResponsProps = AnyObject & {
    code: string | number,
    message: string,
}
const request = async (url: string, params?: any, method: Method = 'GET', options?: AnyObject): Promise<any> => {

    if (!url.startsWith('/')) {
        url = "/" + url
    }
    if (!url.startsWith('/api')) {
        url = '/api' + url
    }
    const {notice, ...configure} = options || {}
    configure['headers'] = {
        "Authorization": `Bearer ${authencation.getToken()}`,
        "Content-Type": "application/json;charset=UTF-8",
    }
    configure.method = method
    switch (method.toLowerCase()) {
        // eslint-disable-next-line no-lone-blocks
        case 'get': {
            configure.params = params || {}
        }
            break;
        // eslint-disable-next-line no-lone-blocks
        case 'delete': {
            configure.params = params || {}
        }
            break;
        // eslint-disable-next-line no-lone-blocks
        case 'post': {
            if (params instanceof FormData) {
                configure.headers['Content-Type'] = 'multipart/form-data'
            }
            configure.data = params || {}
        }
            break;
        default: {
            return Promise.reject('未定义请求类型：Method')
        }
    }

    // 测试环境打印接口请求信息
    // if (process.env.NODE_ENV === 'development') {
    //     console.log('request configure', url, configure)
    // }

    try {
        return instance(url, configure).catch((error: AnyObject) => {
            // if (notice !== false) {
            //     let message: string = `${error.message || '接口异常'}`;
            //     alert(message)
            // }
            return Promise.reject(error)
        });
    } catch (error: any) {
        console.log('error', error)
        return Promise.reject({code: 'system.error', message: error.message});
    }
}

const getRequest = (url: string, params?: any, options?: AnyObject) => {
    return request(url, params, 'GET', options)
}

const postRequest = (url: string, params?: any, options?: AnyObject) => {
    return request(url, params, 'POST', options)
}

const deleteRequest = (url: string, params?: any, options?: AnyObject) => {
    return request(url, params, 'DELETE', options)
}

const patchRequest = (url: string, params?: any, options?: AnyObject) => {
    if (params instanceof FormData) {
        params.append('_method', 'patch')
    } else {
        params = {...(params || {}), _method: 'patch'}
    }
    return request(url, params, 'POST', options)
}

export default attachPropertiesToComponent(request, {
    get: getRequest,
    post: postRequest,
    delete: deleteRequest,
    patch: patchRequest,
});